<script lang="tsx">
/**
 * 表单组件
 */
export default {
  name: "sheet-form"
}
</script>

<script lang="tsx" setup>
import SheetFormManager from "./sheet-form-manager.ts"
import {ref, defineProps, watch} from "vue"
import {cloneDeep} from "lodash"
import Render from "@/frame/components/core/render/index.vue"

/**
 * 定义props
 */
const propsData = defineProps<{
  SheetFormModel: SheetFormManager<any>
  reflections?: any;
}>()

/**
 * 表单模型
 */
const sheetFormModel = ref<SheetFormManager<any>>()

/**
 * 表单数据
 */
const sheetFormData = ref<any>({})

/**
 * 监听
 */
watch(() => propsData.SheetFormModel, function (newValue: any) {
  if (newValue) {
    sheetFormModel.value = newValue
  }
}, {
  deep: true,
  immediate: true
})

/**
 * 初始化表单数据
 */
const initFormData = () => {
  if (sheetFormModel.value?.initValue) {
    setFormData(sheetFormModel.value?.initValue)
  } else {
    setFormData({})
  }
}

/**
 * 设置组件值
 */
const handleSetData = (item?: any) => {
  if (item) {
    sheetFormData.value[item.key] = item.value
  }
}

/**
 * 获取表单原始数据
 */
const getFormData = async () => {
  if (sheetFormModel.value?.beforeSubmit) {
    return await sheetFormModel.value.beforeSubmit(sheetFormData.value)
  }
  return sheetFormData.value
}

/**
 * 设置表单数据
 */
const setFormData = async (data: any) => {
  if (typeof (sheetFormModel.value?.bindData) === "function") {
    let result = sheetFormModel.value.bindData(data)
    if (result instanceof Promise) {
      result = await result
    }
    sheetFormData.value = cloneDeep(result)
  } else {
    sheetFormData.value = cloneDeep(data)
  }
}

/**
 * 暴露
 */
defineExpose({
  initFormData,
  getFormData,
  setFormData
})
</script>

<template>
  <div class="sheet-form">
    <div class="form-content">
      <el-form v-model="sheetFormData">
        <el-form-item v-for="(item, index) in sheetFormModel?.els" v-show="!item.hide" :key="index"
                      :label="item.label" :label-width="sheetFormModel?.labelWidth">
          <Render :data="sheetFormData" :item="item" :reflections="propsData.reflections" @setData="handleSetData"/>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>